/*
 * Copyright 2008 Carnegie Mellon University
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, 
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package edu.cmu.lti.sepia.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONObject;

import edu.cmu.lti.sepia.api.json.JsonAction;
import edu.cmu.lti.sepia.data.db.SQL;

public class JsonFacade extends HttpServlet {
	
	private static final long serialVersionUID = 1L;
	
	@Override
    public void doGet( HttpServletRequest request, HttpServletResponse response )
			throws IOException, ServletException {

		// Write response header
		request.setCharacterEncoding("UTF8");
		//don't specify json content type
		//response.setContentType("text/javascript+json; charset=utf-8");
		response.setContentType("text/html; charset=utf-8");
		response.setHeader("progma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		
		PrintWriter out = response.getWriter();
		
		if ( request.getParameter("action") == null ) {
			out.println( "Please specify appropriate arguments<br>" );
			out.println( "Example: json?action=QAEvalPools&language=JA<br>");
			out.println( "List of actions: <br>");
			for ( JsonAction ja : JsonAction.values() ) {
				out.println( "&nbsp;&nbsp;&nbsp;&nbsp;"+ja.toString() );
			}
			return;
		}

		StringBuilder params = new StringBuilder();
    for (Enumeration<?> e = request.getParameterNames(); e.hasMoreElements();) {
      String key = (String) e.nextElement();
      Object obj = request.getParameter(key);
      if (obj.getClass().equals(String.class)) {
        params.append(key + " = " + (String) obj + "\n");
      }
      if (!obj.getClass().equals(String.class)) {
        params.append(key + " = " + obj + "\n");
      }
    }
		
    SQL sql = new SQL();
		try {
			JsonAction action = JsonAction.valueOf(request.getParameter("action"));
			JSONObject json = action.execute(sql,request);
			out.print(json.toString());
		} catch ( Exception e ) {
		  e.printStackTrace();
		  e.printStackTrace(out);
		  out.print("Input:\n"+params+"\n\n"+e.getMessage() + "<br/>");
		} finally {
		  try {
		    sql.close(); 
      } catch (Exception e2) {}
		}
	}
	
    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response)
	throws IOException, ServletException {
    	doGet( request, response );
    }
    
}
